package com.share.service.impl;

import cn.hutool.db.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.enums.HttpStatusEnum;
import com.share.exception.BaseException;
import com.share.mapper.SysMenuMapper;
import com.share.mapper.SysUserMapper;
import com.share.mapper.UserIdCardCurrentMapper;
import com.share.service.ISysUserService;
import com.share.service.IUserIdCardCurrentService;
import com.share.user.admin.dtos.PayloadDTO;
import com.share.user.admin.dtos.RefreshTokenRequest;
import com.share.user.admin.dtos.SysUserDTO;
import com.share.user.admin.pojos.SysUser;
import com.share.user.admin.pojos.UserIdCardCurrent;
import com.share.user.admin.vo.SysUserVo;
import com.share.user.admin.vo.TokenResponse;
import com.share.user.admin.vo.UserInfoVo;
import com.share.util.common.PrivacyUtils;
import com.share.util.common.StringUtils;
import com.share.util.thread.ThreadLocalUtils;
import com.share.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * 用户服务接口
 */
@Slf4j
@Service
@Transactional
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {


    private final TokenUtils tokenUtils;
    private final IUserIdCardCurrentService userIdCardCurrentService;

    @Autowired
    public SysUserServiceImpl(TokenUtils tokenUtils , IUserIdCardCurrentService userIdCardCurrentService) {
        this.tokenUtils = tokenUtils;
        this.userIdCardCurrentService = userIdCardCurrentService;
    }






    @Override
    public TokenResponse refToken(RefreshTokenRequest request) {
        // 判断token是否过期
        Boolean tokenExpired = tokenUtils.isTokenExpired(request.getRefreshToken());
        if (tokenExpired) {
            throw new BaseException("刷新过期,请重新登陆",Instant.now(),HttpStatusEnum.UNAUTHORIZED);
        }
        // 取出 token 里面的数据
        PayloadDTO payloadDTO = tokenUtils.getClaimsFromToken(request.getRefreshToken());

        String accessToken = tokenUtils.AccessToken(payloadDTO);
        String refreshToken = tokenUtils.refreshToken(accessToken);
        PayloadDTO claimsFromToken = tokenUtils.getClaimsFromToken(accessToken);

        Long exp = claimsFromToken.getExp();
        // 将毫秒时间戳转换为秒时间戳
        Instant instant = Instant.ofEpochMilli(exp);

        // 将 Instant 转换为 LocalDateTime，使用系统默认时区
        LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
        return new TokenResponse(accessToken, refreshToken, localDateTime);
    }


    @Override
    public UserInfoVo getUserInfo() {
        PayloadDTO payloadDTO = ThreadLocalUtils.get();
        QueryWrapper<UserIdCardCurrent> queryWrapperIdCard = new QueryWrapper<>();
        queryWrapperIdCard.eq("user_id", payloadDTO.getId());
        UserIdCardCurrent userIdCardCurrent = userIdCardCurrentService.getBaseMapper().selectOne(queryWrapperIdCard);
        SysUser sysUser = this.getById(payloadDTO.getId());

        if (StringUtils.isNull(userIdCardCurrent)) {
            return new UserInfoVo().builder()
                    .nickname(sysUser.getNickname())
                    .avatar(sysUser.getAvatar())
                    .email(PrivacyUtils.encryptEmail(sysUser.getEmail()))
                    .phone(PrivacyUtils.encryptPhone(sysUser.getPhone()))
                    .lastLoginTime(sysUser.getLastLoginTime())
                    .createTime(sysUser.getCreatedAt())
                    .build();
        }

        return new UserInfoVo().builder()
                .nickname(sysUser.getNickname())
                .avatar(sysUser.getAvatar())
                .email(PrivacyUtils.encryptEmail(sysUser.getEmail()))
                .phone(PrivacyUtils.encryptPhone(sysUser.getPhone()))
                .idNumber(PrivacyUtils.encryptIdCard(userIdCardCurrent.getIdNumber()))
                .name(PrivacyUtils.encryptName(userIdCardCurrent.getName()))
                .lastLoginTime(sysUser.getLastLoginTime())
                .createTime(sysUser.getCreatedAt())
                .build();
    }

}
